package holmes

import (
	"fmt"
	"os"
	"runtime/debug"
	"time"
)

// EveryHour sets new log file created every hour.
func EveryHour(l Logger) Logger {
	l.unit = time.Hour
	return l
}

// EveryMinute sets new log file created every minute.
func EveryMinute(l Logger) Logger {
	l.unit = time.Minute
	return l
}

// AlsoStdout sets log also output to stdio.
func AlsoStdout(l Logger) Logger {
	l.isStdout = true
	return l
}

// PrintStack sets log output the stack trace info.
func PrintStack(l Logger) Logger {
	l.printStack = true
	return l
}

// Debugf prints formatted debug log.
func Debugf(format string, v ...interface{}) {
	loggerInstance.doPrintf(DEBUG, format, v...)
}

// Infof prints formatted info log.
func Infof(format string, v ...interface{}) {
	loggerInstance.doPrintf(INFO, format, v...)
}

// Warnf prints formatted warn log.
func Warnf(format string, v ...interface{}) {
	loggerInstance.doPrintf(WARN, format, v...)
}

// Errorf prints formatted error log.
func Errorf(format string, v ...interface{}) {
	loggerInstance.doPrintf(ERROR, format, v...)
}

func Eventf(format string, v ...interface{}) {
	loggerInstance.doPrintf(EVENT, format, v...)
}

// Fatalf prints formatted fatal log and exits.
func Fatalf(format string, v ...interface{}) {
	loggerInstance.doPrintf(FATAL, format, v...)
	try2Exit()
}

// Debugln prints debug log.
func Debugln(v ...interface{}) {
	loggerInstance.doPrintln(DEBUG, v...)
}

// Infoln prints info log.
func Infoln(v ...interface{}) {
	loggerInstance.doPrintln(INFO, v...)
}

// Warnln prints warn log.
func Warnln(v ...interface{}) {
	loggerInstance.doPrintln(WARN, v...)
}

// Errorln prints error log.
func Errorln(v ...interface{}) {
	loggerInstance.doPrintln(ERROR, v...)
}
func Eventln(v ...interface{}) {
	loggerInstance.doPrintln(EVENT, v...)
}

// Fatalln prints fatal log and exits.
func Fatalln(v ...interface{}) {
	loggerInstance.doPrintln(FATAL, v...)
	try2Exit()
}

func try2Exit() {
	if *distributeMode {
		fmt.Println("等待分布式日志退出")
		//分布式日志模式
		//等待发送完成，超时时间为10秒
		loggerInstance.closeInternet()
		for i := 0; i < 10; i++ {
			if !loggerInstance.isInternetOver() {
				time.Sleep(1 * time.Second)
			} else {
				break
			}
		}

	}
	os.Exit(1)
}

func RecordPanic() {
	if err := recover(); err != nil {
		Fatalln(err, "\n", string(debug.Stack()))
	}
}
